#include "dynamicArrayStack.h"
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 5

int isValid(char* s)
{
    DynamicArrayStack stack;
    dynamicArrayStackInit(&stack);
    char *chInput = NULL;

    while(*s != '\0')
    {
        /* 左边括号*/
        if(*s == '(' || *s == '[' || *s == '{')
        {
            chInput = (char *)malloc(sizeof(char) * 1);//分配空间
            if(chInput == NULL)
            {
                perror("malloc error");
                exit(-1);
            }

            *chInput = *s;
            dynamicArrayStackPush(&stack, (void *)chInput);
        }

        else
        {
            /* 一定是右边括号*/
            if(dynamicArrayStackIsEmpty(&stack) == 1)
            {
                return 0;
            }
            /* 取栈顶元素*/
            char *chOut = NULL; 
            dynamicArrayStackTop(&stack, (void **)&chOut);
            dynamicArrayStackPop(&stack);

            if(*s == ')' && *chOut != '(')
            {
                return 0;
            }
            else if(*s == '}' && *chOut != '{')
            {
                return 0;
            }
            else if(*s == ']' && *chOut != '[')
            {
                return 0;
            }
            
            /* 结束之后一定要在外面释放*/
            if(chOut != NULL)
            {
                free(chOut);
                chOut = NULL;
            }
            
        }
        s++;
    }

    // if(dynamicArrayStackIsEmpty(&stack) == 1)
    // {
    //     return 1;
    // }
    // else
    // {
    //     return 0;
    // }

    int res = dynamicArrayStackIsEmpty(&stack) == 1 ? 1 : 0;

    /* 销毁*/
    dynamicArrayStackDestroy(&stack);


    return res;
}
int main()
{
    
    #if 0
    DynamicArrayStack stack;
    dynamicArrayStackInit(&stack);

    int nums[BUFFER_SIZE] = {11, 22, 33, 44, 55};

    for (int idx = 0; idx < BUFFER_SIZE; idx++)
    {
        dynamicArrayStackPush(&stack, (void *)&nums[idx]);
    }
    
    int size = 0;
    dynamicArrayStackGetSize(&stack, &size);
    printf("size:%d\n", size);

    int *topVal = NULL;
    while (dynamicArrayStackGetSize(&stack, &size) != 0)
    {
        dynamicArrayStackTop(&stack, (void **)&topVal);
        dynamicArrayStackPop(&stack);

        printf("top value:%d\n", *topVal);
    }

    /* 销毁 */
    dynamicArrayStackDestroy(&stack);
    #endif

    char buffer[] = "(){}[]";
    int ret = isValid(buffer);
    printf("ret:%d\n", ret);


}